package com.example.port.service.impl;

import com.example.port.entity.PortArea;
import com.example.port.mapper.PortAreaMapper;
import com.example.port.service.PortAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class PortAreaServiceImpl implements PortAreaService {
    
    private final PortAreaMapper portAreaMapper;
    
    @Autowired
    public PortAreaServiceImpl(PortAreaMapper portAreaMapper) {
        this.portAreaMapper = portAreaMapper;
    }
    
    @Override
    public int insertPortArea(PortArea portArea) {
        // 检查是否已设置ID，如果没有，则自动生成ID
        if (portArea.getAreaId() == null) {
            Integer maxId = portAreaMapper.getMaxAreaId();
            portArea.setAreaId(maxId + 1);
        }
        return portAreaMapper.insert(portArea);
    }
    
    @Override
    public List<PortArea> getAllPortAreas() {
        return portAreaMapper.selectAll();
    }
    
    @Override
    public PortArea getPortAreaById(Integer areaId) {
        return portAreaMapper.selectById(areaId);
    }
    
    @Override
    public int deletePortArea(Integer areaId) {
        return portAreaMapper.delete(areaId);
    }
    
    @Override
    public int updatePortArea(PortArea portArea) {
        return portAreaMapper.update(portArea);
    }
    
    @Override
    public int updatePortAreaUsage(Integer areaId, Double usage) {
        if (areaId == null || usage == null) {
            return 0;
        }
        
        PortArea portArea = portAreaMapper.selectById(areaId);
        if (portArea == null) {
            return 0;
        }
        
        try {
            portArea.setCurrentUsage(BigDecimal.valueOf(usage));
            
            // 更新状态
            BigDecimal maxCapacity = portArea.getMaxCapacity();
            if (maxCapacity != null) {
                if (usage >= maxCapacity.doubleValue()) {
                    portArea.setStatus("已满");
                } else if ("已满".equals(portArea.getStatus())) {
                    portArea.setStatus("可用");
                }
            }
            
            // 打印日志，便于调试
            System.out.println("港口区域 " + areaId + " 使用量更新为: " + usage + 
                              ", 最大容量: " + (maxCapacity != null ? maxCapacity : "未设置") + 
                              ", 状态: " + portArea.getStatus());
            
            return portAreaMapper.update(portArea);
        } catch (Exception e) {
            System.err.println("更新港口区域使用量失败: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }
} 
